package com.zygk.library.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import com.baoyachi.stepview.HorizontalStepsViewIndicator;
import com.baoyachi.stepview.bean.StepBean;
import com.zygk.library.R;
import java.util.ArrayList;
import java.util.List;

/**
 * 日期：16/6/22 14:15
 * <p/>
 * 描述：StepsViewIndicator 指示器
 */
public class MyHorizontalStepsViewIndicator extends HorizontalStepsViewIndicator
{
  //定义默认的高度   definition default height
  private int defaultStepIndicatorNum = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());

  private float mCompletedLineHeight;//完成线的高度     definition completed line height
  private float mCircleRadius;//圆的半径  definition circle radius

  private Drawable mCompleteIcon;//完成的默认图片    definition default completed icon
  private Drawable mAttentionIcon;//正在进行的默认图片     definition default underway icon
  private Drawable mDefaultIcon;//默认的背景图  definition default unCompleted icon
  private float mCenterY;//该view的Y轴中间位置     definition view centerY position
  private float mLeftY;//左上方的Y位置  definition rectangle LeftY position
  private float mRightY;//右下方的位置  definition rectangle RightY position

  private List<StepBean> mStepBeanList ;//当前有几部流程    there are currently few step
  private int mStepNum = 0;
  private float mLinePadding;//两条连线之间的间距  definition the spacing between the two circles

  private List<Float> mCircleCenterPointPositionList;//定义所有圆的圆心点位置的集合 definition all of circles center point list
  private Paint mUnCompletedPaint;//未完成Paint  definition mUnCompletedPaint
  private Paint mCompletedPaint;//完成paint      definition mCompletedPaint
  private int mUnCompletedLineColor = ContextCompat.getColor(getContext(), R.color.uncompleted_color);//定义默认未完成线的颜色  definition
  private int mCompletedLineColor = Color.WHITE;//定义默认完成线的颜色      definition mCompletedLineColor
  private PathEffect mEffects;
  private int mComplectingPosition;//正在进行position   underway position


  private Path mPath;

  private OnDrawIndicatorListener mOnDrawListener;
  private int mScreenWidth;//this screen width

  /**
   * 设置监听
   *
   * @param onDrawListener
   */
  public void setOnDrawListener(OnDrawIndicatorListener onDrawListener)
  {
    mOnDrawListener = onDrawListener;
  }

  /**
   * get圆的半径  get circle radius
   *
   * @return
   */
  public float getCircleRadius()
  {
    return mCircleRadius;
  }


  public MyHorizontalStepsViewIndicator(Context context)
  {
    this(context, null);
  }

  public MyHorizontalStepsViewIndicator(Context context, AttributeSet attrs)
  {
    this(context, attrs, 0);
  }

  public MyHorizontalStepsViewIndicator(Context context, AttributeSet attrs, int defStyle)
  {
    super(context, attrs, defStyle);
    init();
  }

  /**
   * init
   */
  private void init()
  {
    mStepBeanList = new ArrayList<>();
    mPath = new Path();
    mEffects = new DashPathEffect(new float[]{8, 8, 8, 8}, 1);

    mCircleCenterPointPositionList = new ArrayList<>();//初始化

    mUnCompletedPaint = new Paint();
    mCompletedPaint = new Paint();
    mUnCompletedPaint.setAntiAlias(true);
    mUnCompletedPaint.setColor(mUnCompletedLineColor);
    mUnCompletedPaint.setStyle(Paint.Style.STROKE);
    mUnCompletedPaint.setStrokeWidth(2);

    mCompletedPaint.setAntiAlias(true);
    mCompletedPaint.setColor(mCompletedLineColor);
    mCompletedPaint.setStyle(Paint.Style.STROKE);
    mCompletedPaint.setStrokeWidth(2);

    mUnCompletedPaint.setPathEffect(mEffects);
    mCompletedPaint.setStyle(Paint.Style.FILL);

    //已经完成线的宽高 set mCompletedLineHeight
    mCompletedLineHeight = 0.05f * defaultStepIndicatorNum;
    //圆的半径  set mCircleRadius
    //mCircleRadius = 0.28f * defaultStepIndicatorNum;
    mCircleRadius = 0.2f * defaultStepIndicatorNum;
    //线与线之间的间距    set mLinePadding
    mLinePadding = 0.85f * defaultStepIndicatorNum;

    mCompleteIcon = ContextCompat.getDrawable(getContext(), R.drawable.complted);//已经完成的icon
    mAttentionIcon = ContextCompat.getDrawable(getContext(), R.drawable.attention);//正在进行的icon
    mDefaultIcon = ContextCompat.getDrawable(getContext(), R.drawable.default_icon);//未完成的icon
  }

  @Override
  protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
  {
    // http://stackoverflow.com/a/12267248/2276198

    //Minimum width and height if not set
    int desiredWidth = (int) (mStepNum * mCircleRadius * 2 - (mStepNum - 1) * mLinePadding);
    int desiredHeight = defaultStepIndicatorNum;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
      //Must be this size
      width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
      //Can't be bigger than...
      width = Math.min(desiredWidth, widthSize);
    } else {
      //Be whatever you want
      width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
      //Must be this size
      height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
      //Can't be bigger than...
      height = Math.min(desiredHeight, heightSize);
    } else {
      //Be whatever you want
      height = desiredHeight;
    }

    mScreenWidth = width;

    setMeasuredDimension(width, height);
  }

  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh)
  {
    super.onSizeChanged(w, h, oldw, oldh);
    //获取中间的高度,目的是为了让该view绘制的线和圆在该view垂直居中   get view centerY，keep current stepview center vertical
    mCenterY = 0.5f * getHeight();
    //获取左上方Y的位置，获取该点的意义是为了方便画矩形左上的Y位置
    mLeftY = mCenterY - (mCompletedLineHeight / 2);
    //获取右下方Y的位置，获取该点的意义是为了方便画矩形右下的Y位置
    mRightY = mCenterY + mCompletedLineHeight / 2;

    mCircleCenterPointPositionList.clear();

    // 20180130 djy edit
    //float distanceBetweenEach = (mScreenWidth/(mStepNum + 1));
    float distanceBetweenEach = (mScreenWidth/(mStepNum));

    for(int i = 0; i < mStepNum; i++)
    {
      //先计算全部最左边的padding值（getWidth()-（圆形直径+两圆之间距离）*2）
      //float paddingLeft = (mScreenWidth - mStepNum * mCircleRadius * 2 - (mStepNum - 1) * mLinePadding) / 2;
      //            float paddingLeft = (mScreenWidth/ - mStepNum * mCircleRadius * 2 - (mStepNum - 1) * mLinePadding) / 2;
      //            float paddingLeft = 10;
      //add to list

      // 20180130 djy edit
      //mCircleCenterPointPositionList.add(distanceBetweenEach * (i + 1));
      mCircleCenterPointPositionList.add(distanceBetweenEach * (i + (float)0.5));
    }

    /**
     * set listener
     */
    if(mOnDrawListener!=null)
    {
      mOnDrawListener.ondrawIndicator();
    }
  }

  @Override
  protected synchronized void onDraw(Canvas canvas)
  {
    super.onDraw(canvas);
    if(mOnDrawListener!=null)
    {
      mOnDrawListener.ondrawIndicator();
    }
    mUnCompletedPaint.setColor(mUnCompletedLineColor);
    mCompletedPaint.setColor(mCompletedLineColor);

    //-----------------------画线-------draw line-----------------------------------------------
    for(int i = 0; i < mCircleCenterPointPositionList.size() -1; i++)
    {
      //前一个ComplectedXPosition
      final float preComplectedXPosition = mCircleCenterPointPositionList.get(i);
      //后一个ComplectedXPosition
      final float afterComplectedXPosition = mCircleCenterPointPositionList.get(i + 1);

      //if(i <= mComplectingPosition && mStepBeanList.get(0).getState()!= StepBean.STEP_UNDO)//判断在完成之前的所有点
      if(i <= mComplectingPosition && mStepBeanList.get(i).getState()== StepBean.STEP_COMPLETED)//判断在完成之前的所有点
      {
        //判断在完成之前的所有点，画完成的线，这里是矩形,很细的矩形，类似线，为了做区分，好看些
        canvas.drawRect(preComplectedXPosition + mCircleRadius, mLeftY, afterComplectedXPosition - mCircleRadius, mRightY, mCompletedPaint);
      } else
      {
        mPath.moveTo(preComplectedXPosition + mCircleRadius, mCenterY);
        mPath.lineTo(afterComplectedXPosition - mCircleRadius, mCenterY);
        canvas.drawPath(mPath, mUnCompletedPaint);
      }
    }
    //-----------------------画线-------draw line-----------------------------------------------


    //-----------------------画图标-----draw icon-----------------------------------------------
    for(int i = 0; i < mCircleCenterPointPositionList.size(); i++)
    {
      final float currentComplectedXPosition = mCircleCenterPointPositionList.get(i);
      Rect rect = new Rect((int) (currentComplectedXPosition - mCircleRadius), (int) (mCenterY - mCircleRadius), (int) (currentComplectedXPosition + mCircleRadius), (int) (mCenterY + mCircleRadius));

      StepBean stepsBean = mStepBeanList.get(i);

      if(stepsBean.getState()== StepBean.STEP_UNDO)
      {
        mDefaultIcon.setBounds(rect);
        mDefaultIcon.draw(canvas);
      }else if(stepsBean.getState()== StepBean.STEP_CURRENT)
      {
        mCompletedPaint.setColor(Color.WHITE);
        canvas.drawCircle(currentComplectedXPosition, mCenterY, mCircleRadius * 1.1f, mCompletedPaint);
        mAttentionIcon.setBounds(rect);
        mAttentionIcon.draw(canvas);
      }else if(stepsBean.getState()== StepBean.STEP_COMPLETED)
      {
        mCompleteIcon.setBounds(rect);
        mCompleteIcon.draw(canvas);
      }
    }
    //-----------------------画图标-----draw icon-----------------------------------------------
  }

  /**
   * 得到所有圆点所在的位置
   *
   * @return
   */
  public List<Float> getCircleCenterPointPositionList()
  {
    return mCircleCenterPointPositionList;
  }

  /**
   * 设置流程步数
   *
   * @param stepsBeanList 流程步数
   */
  public void setStepNum(List<StepBean> stepsBeanList)
  {
    this.mStepBeanList = stepsBeanList;
    mStepNum = mStepBeanList.size();

    if(mStepBeanList!=null&&mStepBeanList.size()>0)
    {
      for(int i = 0;i<mStepNum;i++)
      {
        StepBean stepsBean = mStepBeanList.get(i);
        {
          if(stepsBean.getState()== StepBean.STEP_COMPLETED)
          {
            mComplectingPosition = i;
          }
        }
      }
    }

    requestLayout();
  }

  /**
   * 设置未完成线的颜色
   *
   * @param unCompletedLineColor
   */
  public void setUnCompletedLineColor(int unCompletedLineColor)
  {
    this.mUnCompletedLineColor = unCompletedLineColor;
  }

  /**
   * 设置已完成线的颜色
   *
   * @param completedLineColor
   */
  public void setCompletedLineColor(int completedLineColor)
  {
    this.mCompletedLineColor = completedLineColor;
  }

  /**
   * 设置默认图片
   *
   * @param defaultIcon
   */
  public void setDefaultIcon(Drawable defaultIcon)
  {
    this.mDefaultIcon = defaultIcon;
  }

  /**
   * 设置已完成图片
   *
   * @param completeIcon
   */
  public void setCompleteIcon(Drawable completeIcon)
  {
    this.mCompleteIcon = completeIcon;
  }

  /**
   * 设置正在进行中的图片
   *
   * @param attentionIcon
   */
  public void setAttentionIcon(Drawable attentionIcon)
  {
    this.mAttentionIcon = attentionIcon;
  }


  /**
   * 设置对view监听
   */
  public interface OnDrawIndicatorListener
  {
    void ondrawIndicator();
  }
}
